home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4786 < prev    next >
Encoding:
Text File  |  1996-08-06  |  38.6 KB  |  971 lines

  1. Path: sun.soe.clarkson.edu!cline
  2. From: cline@sun.soe.clarkson.edu (Marshall Cline)
  3. Newsgroups: comp.lang.c++
  4. Subject: C++ FAQ: posting #2/4
  5. Followup-To: comp.lang.c++
  6. Date: 1 Feb 1996 03:20:20 GMT
  7. Organization: Paradigm Shift, Inc (technology consulting)
  8. Sender: cline@sun.soe.clarkson.edu
  9. Distribution: world
  10. Expires: +1 month
  11. Message-ID: <4epbhk$ghr@library.erc.clarkson.edu>
  12. Reply-To: cline@parashift.com (Marshall Cline)
  13. NNTP-Posting-Host: sun.soe.clarkson.edu
  14. Summary: Please read this before posting to comp.lang.c++
  15.  
  16. comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
  17. Copyright (C) 1991-96 Marshall P. Cline, Ph.D.
  18. Posting 2 of 4.
  19. Posting #1 explains copying permissions, (no)warranty, table-of-contents, etc
  20.  
  21. ==============================================================================
  22. SECTION 9: Freestore management
  23. ==============================================================================
  24.  
  25. Q33: Does "delete p" delete the pointer "p", or the pointed-to-data, "*p"?
  26.  
  27. The pointed-to-data.
  28.  
  29. "delete" really means "delete the thing pointed to by."  The same abuse of
  30. English occurs when "free"ing the memory pointed to by a ptr in C ("free(p)"
  31. really means "free_the_stuff_pointed_to_by(p)").
  32.  
  33. ==============================================================================
  34.  
  35. Q34: Can I "free()" pointers allocated with "new"?  Can I "delete" pointers
  36.    alloc'd with "malloc()"?
  37.  
  38. No.
  39.  
  40. It is perfectly legal, moral, and wholesome to use malloc/free and new/delete
  41. in the same program, but it is illegal, immoral, and despicable to free a
  42. pointer allocated via new, or to delete a pointer allocated via malloc.
  43.  
  44. ==============================================================================
  45.  
  46. Q35: Why should I use "new" instead of trustworthy old malloc()?
  47.  
  48. Constructors/destructors, type safety, overridability.
  49.  
  50. Constructors/destructors: unlike "malloc(sizeof(Fred))", "new Fred()" calls
  51. Fred's constructor.  Similarly, "delete p" calls "*p"'s destructor.
  52.  
  53. Type safety: malloc() returns a "void*" which isn't type safe.  "new Fred()"
  54. returns a ptr of the right type (a "Fred*").
  55.  
  56. Overridability: "new" is an operator that can be overridden by a class, while
  57. "malloc" is not overridable on a per-class basis.
  58.  
  59. ==============================================================================
  60.  
  61. Q36: Why doesn't C++ have a "realloc()" along with "new" and "delete"?
  62.  
  63. To save you from disaster.
  64.  
  65. When realloc() has to copy the allocation, it uses a BITWISE copy operation,
  66. which will tear most C++ objects to shreds.  C++ objects should be allowed to
  67. copy themselves: they use their own copy constructor or assignment operator.
  68.  
  69. ==============================================================================
  70.  
  71. Q37: How do I allocate / unallocate an array of things?
  72.  
  73. Use new[] and delete[]:
  74.  
  75.     Fred* p = new Fred[100];
  76.     //...
  77.     delete [] p;
  78.  
  79. Any time you use the "[...]" in the "new" expression, you *!*MUST*!* use "[]"
  80. in the "delete" statement.  This syntax is necessary because there is no
  81. syntactic difference between a pointer to a thing and a pointer to an array of
  82. things (something we inherited from C).
  83.  
  84. ==============================================================================
  85.  
  86. Q38: What if I forget the "[]" when "delete"ing array allocated via "new
  87.    Fred[n]"?
  88.  
  89. All life comes to a catastrophic end.
  90.  
  91. It is the programmer's --not the compiler's-- responsibility to get the
  92. connection between new[] and delete[] correct.  If you get it wrong, neither a
  93. compile-time nor a run-time error message will be generated by the compiler.
  94. Heap corruption is a likely result.  Or worse.  Your program will probably die.
  95.  
  96. ==============================================================================
  97.  
  98. Q39: Is it legal (and moral) for a member function to say "delete this"?
  99.  
  100. As long as you're careful, you'll be ok.
  101.  
  102. Here's how I define "careful":
  103. 1) You're absolutely 100% positive sure that "this" was allocated via "new"
  104.    (not by "new[]", nor by placement "new", by by plain ordinary "new").
  105. 2) You're absolutely 100% positive sure that your member function will be
  106.    the last member function invoked on this object.
  107. 3) After you do the suicide thing ("delete this;"), you must not touch any
  108.    piece of "this" object, including data or methods.
  109. 4) After you do the suicide thing ("delete this;"), you must not touch the
  110.    "this" pointer.  In other words, you must not examine it, compare it with
  111.    another pointer or with NULL, print it, cast it, do anything with it.
  112.  
  113. Naturally the usual caveats apply in cases where your "this" pointer is a
  114. pointer to a base class and the destructor isn't virtual.
  115.  
  116. ==============================================================================
  117.  
  118. Q40: How do I allocate multidimensional arrays using new?
  119.  
  120. There are many ways to do this, depending on how flexible you want the array
  121. sizing to be.  On one extreme, if you know all the dimensions at compile-time,
  122. you can allocate multidimensional arrays statically (as in C):
  123.  
  124.     class Fred { /*...*/ };
  125.  
  126.     void manipulateArray()
  127.     {
  128.       Fred matrix[10][20];
  129.  
  130.       //use matrix[i][j]...
  131.  
  132.       //no need for explicit deallocation
  133.     }
  134.  
  135. On the other extreme, if you want to allow the various slices of the matrix to
  136. have a different sizes, you can allocate everything off the freestore:
  137.  
  138.     void manipulateArray(unsigned nrows, unsigned ncols[])
  139.     //'nrows' is the number of rows in the array.
  140.     //therefore valid row numbers are from 0 to nrows-1 inclusive.
  141.     //'ncols[r]' is the number of columns in row 'r' ('r' in [0..nrows-1]).
  142.     {
  143.       Fred** matrix = new Fred*[nrows];
  144.       for (unsigned r = 0; r < nrows; ++r)
  145.         matrix[r] = new Fred[ ncols[r] ];
  146.  
  147.       //use matrix[i][j]...
  148.  
  149.       //deletion is the opposite of allocation:
  150.       for (r = nrows; r > 0; --r)
  151.         delete [] matrix[r-1];
  152.       delete [] matrix;
  153.     }
  154.  
  155. ==============================================================================
  156.  
  157. Q41: Does C++ have arrays whose length can be specified at run-time?
  158.  
  159. Yes, in the sense that STL has a vector template that provides this behavior.
  160. See on "STL" in the "Libraries" section.
  161.  
  162. No, in the sense that built-in array types need to have their length specified
  163. at compile time.
  164.  
  165. Yes, in the sense that even built-in array types can specify the first index
  166. bounds at run-time.  E.g., comparing with the previous FAQ, if you only need
  167. the first array dimension to vary, then you can just ask new for an array of
  168. arrays (rather than an array of pointers to arrays):
  169.  
  170.     const unsigned ncols = 100;
  171.     //'ncols' is not a run-time variable (number of columns in the array)
  172.  
  173.     class Fred { ... };
  174.  
  175.     void manipulateArray(unsigned nrows)
  176.     //'nrows' is a run-time variable (number of rows in the array)
  177.     {
  178.       Fred (*matrix)[ncols] = new Fred[nrows][ncols];
  179.  
  180.       //use matrix[i][j]
  181.  
  182.       //deletion is the opposite of allocation:
  183.       delete [] matrix;
  184.     }
  185.  
  186. You can't do this if you need anything other than the first dimension
  187. of the array to change at run-time.
  188.  
  189. ==============================================================================
  190.  
  191. Q42: How can I ensure objects of my class are always created via "new" rather
  192.    than as locals or global/static objects?
  193.  
  194. Make sure the class's constructors are "private:", and define "friend" or
  195. "static" fns that return a ptr to the objects created via "new" (make the
  196. constructors "protected:" if you want to allow derived classes).
  197.  
  198.     class Fred {    //only want to allow dynamicly allocated Fred's
  199.     public:
  200.       static Fred* create()                 { return new Fred();     }
  201.       static Fred* create(int i)            { return new Fred(i);    }
  202.       static Fred* create(const Fred& fred) { return new Fred(fred); }
  203.     private:
  204.       Fred();
  205.       Fred(int i);
  206.       Fred(const Fred& fred);
  207.       virtual ~Fred();
  208.     };
  209.  
  210.     main()
  211.     {
  212.       Fred* p = Fred::create(5);
  213.       ...
  214.       delete p;
  215.     }
  216.  
  217. ==============================================================================
  218. SECTION 10: Debugging and error handling
  219. ==============================================================================
  220.  
  221. Q43: How can I handle a constructor that fails?
  222.  
  223. Throw an exception.
  224.  
  225. Constructors don't have a return type, so it's not possible to use error codes.
  226. The best way to signal constructor failure is therefore to throw an exception.
  227.  
  228. Before C++ had exceptions, we signaled constructor failure by putting the
  229. object into a "half baked" state (e.g., by setting an internal status bit).
  230. There was a query ("inspector") method to check this bit, that allowed clients
  231. to discover whether they had a live object.  Other member functions would also
  232. check this bit, and, if the object wasn't really alive, do a no-op (or perhaps
  233. something more obnoxious such as "abort()").  This was really ugly.
  234.  
  235. ==============================================================================
  236.  
  237. Q44: How should I handle resources if my constructors may throw exceptions?
  238.  
  239. Every data member inside your object should clean up its own mess.
  240.  
  241. If a constructor throws an exception, the object's destructor is NOT run.  If
  242. your object has already done something that needs to be undone (such as
  243. allocating some memory, opening a file, or locking a semaphore), this "stuff
  244. that needs to be undone" MUST be remembered by a data member inside the object.
  245.  
  246. For example, rather than allocating memory into a raw "Fred*" data member, put
  247. the allocated memory into a "smart pointer" member object, and the destructor
  248. of this smart pointer will delete the Fred object when the smart pointer dies.
  249.  
  250. ==============================================================================
  251. SECTION 11: Const correctness
  252. ==============================================================================
  253.  
  254. Q45: What is "const correctness"?
  255.  
  256. A good thing.
  257.  
  258. Const correctness uses the keyword "const" to ensure const objects don't get
  259. mutated.  E.g., if function "f()" accepts a "String", and "f()" wants to
  260. promise not to change the "String", you:
  261.  
  262.  * can either pass by value:    void  f(      String  s   )  { /*...*/ }
  263.  * or by constant reference:    void  f(const String& s   )  { /*...*/ }
  264.  * or by constant pointer:    void  f(const String* sptr)  { /*...*/ }
  265.  * but NOT by non-const ref:    void  f(      String& s   )  { /*...*/ }
  266.  * NOR by non-const pointer:    void  f(      String* sptr)  { /*...*/ }
  267.  
  268. Attempted changes to "s" within a fn that takes a "const String&" are flagged
  269. as compile-time errors; neither run-time space nor speed is degraded.
  270.  
  271. Declaring the "constness" of a parameter is just another form of type safety.
  272. It is almost as if a constant String, for example, "lost" its various mutative
  273. operations.  If you find type safety helps you get systems correct (it does;
  274. especially in large systems), you'll find const correctness helps also.
  275.  
  276. ==============================================================================
  277.  
  278. Q46: Should I try to get things const correct "sooner" or "later"?
  279.  
  280. At the very, very, VERY beginning.
  281.  
  282. Back-patching const correctness results in a snowball effect: every "const" you
  283. add "over here" requires four more to be added "over there."
  284.  
  285. ==============================================================================
  286.  
  287. Q47: What is a "const member function"?
  288.  
  289. A member function that inspects (rather than mutates) its object.
  290.  
  291.     class Fred {
  292.     public:
  293.       void f() const;
  294.     };      // ^^^^^--- this implies "fred.f()" won't change "fred"
  295.  
  296. This means that the ABSTRACT (client-visible) state of the object isn't going
  297. to change (as opposed to promising that the "raw bits of the object's struct
  298. aren't going to change).  C++ compilers aren't allowed to take the "bitwise"
  299. interpretation, since a non-const alias could exist which could modify the
  300. state of the object (gluing a "const" ptr to an object doesn't promise the
  301. object won't change; it promises only that the object won't change VIA THAT
  302. POINTER).
  303.  
  304. "const" member functions are often called "inspectors."  Non-"const" member
  305. functions are often called "mutators."
  306.  
  307. ==============================================================================
  308.  
  309. Q48: What do I do if I want to update an "invisible" data member inside a
  310.    "const" member function?
  311.  
  312. Use "mutable", or use "const_cast".
  313.  
  314. A small percentage of inspectors need to make innocuous changes to data members
  315. (e.g., a "Set" object might want to cache its last lookup in hopes of improving
  316. the performance of its next lookup).  By saying the changes are "inocuous," I
  317. mean that the changes wouldn't be visible from outside the object's interface
  318. (otherwise the method would be a mutator rather than an inspector).
  319.  
  320. When this happens, the data member which will be modified should be marked as
  321. "mutable" (put the "mutable" keyword just before the data member's declaration;
  322. i.e., in the same place where you could put "const").  This tells the compiler
  323. that the data member is allowed to change during a const member function.  If
  324. you can't use "mutable", you can cast away the constness of "this" via
  325. "const_cast".  E.g., in "Set::lookup() const", you might say,
  326.  
  327.     Set* self = const_cast<Set*>(this);
  328.  
  329. After this line, "self" will have the same bits as "this" (e.g., "self==this"),
  330. but "self" is a "Set*" rather than a "const Set*".  Therefore you can use
  331. "self" to modify the object pointed to by "this".
  332.  
  333. ==============================================================================
  334.  
  335. Q49: Does "const_cast" mean lost optimization opportunities?
  336.  
  337. In theory, yes; in practice, no.
  338.  
  339. Even if a compiler outlawed "const_cast", the only way to avoid flushing the
  340. register cache across a "const" member function call would be to ensure that
  341. there are no non-const pointers that alias the object.  This can happen only in
  342. rare cases (when the object is constructed in the scope of the const member fn
  343. invocation, and when all the non-const member function invocations between the
  344. object's construction and the const member fn invocation are statically bound,
  345. and when every one of these invocations is also "inline"d, and when the
  346. constructor itself is "inline"d, and when any member fns the constructor calls
  347. are inline).
  348.  
  349. ==============================================================================
  350. SECTION 12: Inheritance
  351. ==============================================================================
  352.  
  353. Q50: Is inheritance important to C++?
  354.  
  355. Yep.
  356.  
  357. Inheritance is what separates abstract data type (ADT) programming from OOP.
  358.  
  359. ==============================================================================
  360.  
  361. Q51: When would I use inheritance?
  362.  
  363. As a specification device.
  364.  
  365. Human beings abstract things on two dimensions: part-of and kind-of.  A Ford
  366. Taurus is-a-kind-of-a Car, and a Ford Taurus has-a Engine, Tires, etc.  The
  367. part-of hierarchy has been a part of software since the ADT style became
  368. relevant; inheritance adds "the other" major dimension of decomposition.
  369.  
  370. ==============================================================================
  371.  
  372. Q52: How do you express inheritance in C++?
  373.  
  374. By the ": public" syntax:
  375.  
  376.     class Car : public Vehicle {
  377.             //^^^^^^^^---- ": public" is pronounced "is-a-kind-of-a'
  378.       //...
  379.     };
  380.  
  381. We state the above relationship in several ways:
  382.  * Car is "a kind of a" Vehicle
  383.  * Car is "derived from" Vehicle
  384.  * Car is "a specialized" Vehicle
  385.  * Car is the "subclass" of Vehicle
  386.  * Vehicle is the "base class" of Car
  387.  * Vehicle is the "superclass" of Car (this not as common in the C++ community)
  388.  
  389. ==============================================================================
  390.  
  391. Q53: Is it ok to convert a pointer from a derived class to its base class?
  392.  
  393. Yes.
  394.  
  395. A derived class is a specialized version of the base class ("Derived is a
  396. kind-of Base").  The upward conversion is perfectly safe, and happens all the
  397. time (if I am pointing at a car, I am in fact pointing at a vehicle):
  398.  
  399.     void f(Vehicle* v);
  400.     void g(Car* c) { f(c); }    //perfectly safe; no cast
  401.  
  402. Note that the answer to this FAQ assumes we're talking about "public"
  403. inheritance; see below on "private/protected" inheritance for "the other kind".
  404.  
  405. ==============================================================================
  406.  
  407. Q54: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?
  408.  
  409. C++ allows a Derived* to be converted to a Base*, since a Derived object is a
  410. kind of a Base object.  However trying to convert a Derived** to a Base** is
  411. (correctly) flagged as an error (if it was allowed, the Base** could be
  412. dereferenced (yielding a Base*), and the Base* could be made to point to an
  413. object of a DIFFERENT derived class.  This would be an error.
  414.  
  415. As a corollary, an array of Deriveds is-NOT-a-kind-of array of Bases.  At
  416. Paradigm Shift, Inc. we use the following example in our C++ training sessions:
  417.  
  418.                "A bag of apples is NOT a bag of fruit".
  419.  
  420. If a bag of apples COULD be passed as a bag of fruit, someone could put a
  421. banana into the bag of apples!
  422.  
  423. ==============================================================================
  424.  
  425. Q55: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are
  426.    bad?
  427.  
  428. Yes, "arrays are evil" (jest kidd'n :-).
  429.  
  430. There's a very subtle problem with using raw built-in arrays.  Consider this:
  431.  
  432.     void f(Base* arrayOfBase)
  433.     {
  434.       arrayOfBase[3].memberfn();
  435.     }
  436.  
  437.     main()
  438.     {
  439.       Derived arrayOfDerived[10];
  440.       f(arrayOfDerived);
  441.     }
  442.  
  443. The compiler thinks this is perfectly type-safe, since it can convert a
  444. Derived* to a Base*.  But in reality it is horrendously evil: since Derived
  445. might be larger than Base, the array index in f() not only isn't type safe, it
  446. may not even be pointing at a real object!  In general it'll be pointing
  447. somewhere into the innards of some poor Derived.
  448.  
  449. The root problem is that C++ can't distinguish between a ptr-to-a-thing and a
  450. ptr-to-an-array-of-things.  Naturally C++ "inherited" this feature from C.
  451.  
  452. NOTE: if we had used an array-like CLASS instead of using a raw array (e.g., an
  453. "Array<T>" rather than a "T[]"), this problem would have been properly trapped
  454. as an error at compile time rather than at run-time.
  455.  
  456. ==============================================================================
  457. SUBSECTION 12A: Inheritance -- Virtual functions
  458. ==============================================================================
  459.  
  460. Q56: What is a "virtual member function"?
  461.  
  462. A virtual function allows derived classes to replace the implementation
  463. provided by the base class.  The compiler ensures the replacement is always
  464. called whenever the object in question is actually of the derived class, even
  465. if the object is accessed by a base pointer rather than a derived pointer.
  466. This allows algorithms in the base class to be replaced in the derived class,
  467. even if users don't know about the derived class.
  468.  
  469. Note: the derived class can partially replace ("override") the base class
  470. method (the derived class method can invoke the base class version if desired).
  471.  
  472. ==============================================================================
  473.  
  474. Q57: How can C++ achieve dynamic binding yet also static typing?
  475.  
  476. In the following discussion, "ptr" means either a pointer or a reference.
  477.  
  478. When you have a ptr, there are two types: the (static) type of the ptr, and the
  479. (dynamic) type of the pointed-to object (the object may actually be of a class
  480. that is derived from the class of the ptr).
  481.  
  482. "Static typing" means that the "legality" of the call is checked based on the
  483. static type of the ptr: if the type of the ptr can handle the member fn,
  484. certainly the pointed-to object can handle it as well.
  485.  
  486. "Dynamic binding" means that the "code" that is called is based on the dynamic
  487. type of the pointed-to object.  This is called "dynamic binding," since the
  488. actual code being called is determined dynamically (at run time).
  489.  
  490. ==============================================================================
  491.  
  492. Q58: Should a derived class replace ("override") a non-virtual fn from a base
  493.    class?
  494.  
  495. It's legal, but it ain't moral.
  496.  
  497. Experienced C++ programmers will sometimes redefine a non-virtual fn for
  498. efficiency (the alternate implementation might make better use of the derived
  499. class' resources), or to get around the hiding rule (see below, and ARM
  500. ["Annotated Reference Manual"] sect.13.1).  However the client-visible effects
  501. must be IDENTICAL, since non-virtual fns are dispatched based on the static
  502. type of the ptr/ref rather than the dynamic type of the pointed-to/referenced
  503. object.
  504.  
  505. ==============================================================================
  506.  
  507. Q59: What's the meaning of, "Warning: Derived::f(int) hides Base::f(float)"?
  508.  
  509. It means you're going to die.
  510.  
  511. Here's the mess you're in: if Derived declares a member function named "f", and
  512. Base declares a member function named "f" with a different signature (e.g.,
  513. different parameter types and/or constness), then the Base "f" is "hidden"
  514. rather than "overloaded" or "overridden" (even if the Base "f" is virtual).
  515.  
  516. Here's how you get out of the mess: Derived must redefine the Base member
  517. function(s) that are hidden (even if they are non-virtual).  Normally this
  518. re-definition merely calls the appropriate Base member function.  E.g.,
  519.  
  520.     class Base {
  521.     public:
  522.       void f(int);
  523.     };
  524.  
  525.     class Derived : public Base {
  526.     public:
  527.       void f(double);
  528.       void f(int i) { Base::f(i); }
  529.     };             // ^^^^^^^^^^--- redefinition merely calls Base::f(int)
  530.  
  531. ==============================================================================
  532. SUBSECTION 12B: Inheritance -- Conformance
  533. ==============================================================================
  534.  
  535. Q60: Should I hide public member fns inherited from my base class?
  536.  
  537. Never, never, never do this.  Never.  NEVER!
  538.  
  539. Attempting to hide (eliminate, revoke) inherited public member functions is an
  540. all-too-common design error.  It usually stems from muddy thinking.
  541.  
  542. ==============================================================================
  543.  
  544. Q61: Is a "Circle" a kind-of an "Ellipse"?
  545.  
  546. Not if Ellipse promises to be able to change its size asymmetrically.
  547.  
  548. For example, suppose Ellipse has a "setSize(x,y)" method, and suppose this
  549. method promises "the Ellipse's width() will be x, and its height() will be y".
  550. In this case, Circle can't be a kind-of Ellipse.  Simply put, if Ellipse can do
  551. something Circle can't, then Circle can't be a kind of Ellipse.
  552.  
  553. This leaves two potential (valid) relationships between Circle and Ellipse:
  554.  * Make Circle and Ellipse completely unrelated classes.
  555.  * Derive Circle and Ellipse from a base class representing "Ellipses that
  556.    can't NECESSARILY perform an unequal-setSize operation."
  557.  
  558. In the first case, Ellipse could be derived from class "AsymmetricShape" (with
  559. setSize(x,y) being introduced in AsymmetricShape), and Circle could be derived
  560. from "SymmetricShape," which has a setSize(size) member fn.
  561.  
  562. In the second case, class "Oval" could only have "setSize(size)" which sets
  563. both the "width()" and the "height()" to "size", then derive both Ellipse and
  564. Circle from Oval.  Ellipse --but not Circle-- adds the "setSize(x,y)" operation
  565. (see the "hiding rule" for a caveat if the same method name "setSize()" is used
  566. for both operations).
  567.  
  568. ==============================================================================
  569.  
  570. Q62: Are there other options to the "Circle is/isnot kind-of Ellipse"
  571.    dilemma?
  572.  
  573. If you claim that all Ellipses can be squashed asymmetrically, and you claim
  574. that Circle is a kind-of Ellipse, and you claim that Circle can't be squashed
  575. asymmetrically, clearly you've got to adjust (revoke, actually) one of your
  576. claims.  Thus you've either got to get rid of "Ellipse::setSize(x,y)", get rid
  577. of the inheritance relationship between Circle and Ellipse, or admit that your
  578. "Circle"s aren't necessarily circular.
  579.  
  580. Here are the two most common traps new OO/C++ programmers regularly fall into.
  581. They attempt to use coding hacks to cover up a broken design (they redefine
  582. Circle::setSize(x,y) to throw an exception, call "abort()", or choose the
  583. average of the two parameters, or to be a no-op).  Unfortunately all these
  584. hacks will surprise users, since users are expecting "width() == x" and
  585. "height() == y".
  586.  
  587. The only rational way out of this would be to weaken the promise made by
  588. Ellipse's "setSize(x,y)" (e.g., you'd have to change it to, "This method MIGHT
  589. set width() to x and height() to y, or it might do NOTHING").  Unfortunately
  590. this dilutes the contract into dribble, since the user can't rely on any
  591. meaningful behavior.  The whole hierarchy therefore begins to be worthless
  592. (it's hard to convince someone to use an object if you have to shrug your
  593. shoulders when asked what the object does for them).
  594.  
  595. ==============================================================================
  596. SUBSECTION 12C: Inheritance -- Access rules
  597. ==============================================================================
  598.  
  599. Q63: Why can't my derived class access "private" things from my base class?
  600.  
  601. To protect you from future changes to the base class.
  602.  
  603. Derived classes do not get access to private members of a base class.  This
  604. effectively "seals off" the derived class from any changes made to the private
  605. members of the base class.
  606.  
  607. ==============================================================================
  608.  
  609. Q64: What's the difference between "public:", "private:", and "protected:"?
  610.  
  611. "Private:" is discussed in the previous section, and "public:" means "anyone
  612. can access it."  The third option, "protected:", makes a member (either data
  613. member or member fn) accessible to subclasses.
  614.  
  615. ==============================================================================
  616.  
  617. Q65: How can I protect subclasses from breaking when I change internal parts?
  618.  
  619. A class has two distinct interfaces for two distinct sets of clients:
  620.  * its "public:" interface serves unrelated classes.
  621.  * its "protected:" interface serves derived classes.
  622.  
  623. Unless you expect all your subclasses to be built by your own team, you should
  624. consider making your base class's bits be "private:", and use "protected:"
  625. inline access functions to access these data.  This way the private bits can
  626. change, but the derived class's code won't break unless you change the
  627. protected access functions.
  628.  
  629. ==============================================================================
  630. SUBSECTION 12D: Inheritance -- Constructors and destructors
  631. ==============================================================================
  632.  
  633. Q66: When my base class's constructor calls a virtual function, why doesn't my
  634.    derived class's override of that virtual function get invoked?
  635.  
  636. During the Base class's constructor, the object isn't yet a Derived, so if
  637. "Base::Base()" calls a virtual function "virt()", the "Base::virt()" will be
  638. invoked, even if "Derived::virt()" exists.
  639.  
  640. Similarly, during Base's destructor, the object is no longer a Derived, so when
  641. Base::~Base() calls "virt()", "Base::virt()" gets control, NOT the
  642. "Derived::virt()" override.
  643.  
  644. You'll quickly see the wisdom of this approach when you imagine the disaster if
  645. "Derived::virt()" touched a member object from the Derived class.
  646.  
  647. ==============================================================================
  648.  
  649. Q67: Does a derived class destructor need to explicitly call the base
  650.    destructor?
  651.  
  652. No, never explicitly call a destructor (where "never" means "rarely").
  653.  
  654. A derived class's destructor (whether or not you explicitly define one)
  655. AUTOMATICALLY invokes the destructors for member objects and base class
  656. subobjects.  Member objects are destroyed in the reverse order they appear
  657. within the class, then base class subobjects are destroyed in the reverse order
  658. that they appear in the class's list of base classes.
  659.  
  660. You should explicitly call a destructor ONLY in esoteric situations, such as
  661. when destroying an object created by the "placement new operator."
  662.  
  663. ==============================================================================
  664. SUBSECTION 12E: Inheritance -- Private and protected inheritance
  665. ==============================================================================
  666.  
  667. Q68: How do you express "private inheritance"?
  668.  
  669. When you use ": private" instead of ": public."  E.g.,
  670.  
  671.     class Foo : private Bar {
  672.       //...
  673.     };
  674.  
  675. ==============================================================================
  676.  
  677. Q69: How are "private inheritance" and "composition" similar?
  678.  
  679. Private inheritance is a syntactic variant of composition (has-a).
  680.  
  681. E.g., the "car has-a engine" relationship can be expressed using composition:
  682.  
  683.     class Engine {
  684.     public:
  685.       Engine(int numCylinders);
  686.       void start();            //starts this Engine
  687.     };
  688.  
  689.     class Car {
  690.     public:
  691.       Car() : e_(8) { }        //initializes this Car with 8 cylinders
  692.       void start() { e_.start(); }    //start this Car by starting its engine
  693.     private:
  694.       Engine e_;
  695.     };
  696.  
  697. The same "has-a" relationship can also be expressed using private inheritance:
  698.  
  699.     class Car : private Engine {
  700.     public:
  701.       Car() : Engine(8) { }        //initializes this Car with 8 cylinders
  702.       Engine::start;        //start this Car by starting its engine
  703.     };
  704.  
  705. There are several similarities between these two forms of composition:
  706.  * in both cases there is exactly one Engine member object contained in a Car.
  707.  * in neither case can users (outsiders) convert a Car* to an Engine*.
  708.  
  709. There are also several distinctions:
  710.  * the first form is needed if you want to contain several Engines per Car.
  711.  * the second form can introduce unnecessary multiple inheritance.
  712.  * the second form allows members of Car to convert a Car* to an Engine*.
  713.  * the second form allows access to the "protected" members of the base class.
  714.  * the second form allows Car to override Engine's virtual functions.
  715.  
  716. Note that private inheritance is usually used to gain access into the
  717. "protected:" members of the base class, but this is usually a short-term
  718. solution (translation: a band-aid; see below).
  719.  
  720. ==============================================================================
  721.  
  722. Q70: Which should I prefer: composition or private inheritance?
  723.  
  724. Composition.
  725.  
  726. Normally you don't WANT to have access to the internals of too many other
  727. classes, and private inheritance gives you some of this extra power (and
  728. responsibility).  But private inheritance isn't evil; it's just more expensive
  729. to maintain, since it increases the probability that someone will change
  730. something that will break your code.
  731.  
  732. A legitimate, long-term use for private inheritance is when you want to build a
  733. class Fred that uses code in a class Wilma, and the code from class Wilma needs
  734. to invoke methods from your new class, Fred.  In this case, Fred calls
  735. non-virtuals in Wilma, and Wilma calls (usually pure) virtuals in itself, which
  736. are overridden by Fred.  This would be much harder to do with composition.
  737.  
  738.     class Wilma {
  739.     protected:
  740.       void fredCallsWilma()
  741.         { cout << "Wilma::fredCallsWilma()\n"; wilmaCallsFred(); }
  742.       virtual void wilmaCallsFred() = 0;
  743.     };
  744.  
  745.     class Fred : private Wilma {
  746.     public:
  747.       void barney()
  748.         { cout << "Fred::barney()\n"; Wilma::fredCallsWilma(); }
  749.     protected:
  750.       virtual void wilmaCallsFred()
  751.         { cout << "Fred::wilmaCallsFred()\n"; }
  752.     };
  753.  
  754. ==============================================================================
  755.  
  756. Q71: Should I pointer-cast from a "privately" derived class to its base
  757.    class?
  758.  
  759. Generally, No.
  760.  
  761. From a method or friend of a privately derived class, the relationship to the
  762. base class is known, and the upward conversion from PrivatelyDer* to Base* (or
  763. PrivatelyDer& to Base&) is safe; no cast is needed or recommended.
  764.  
  765. However users of PrivateDer should avoid this unsafe conversion, since it is
  766. based on a "private" decision of PrivateDer, and is subject to change without
  767. notice.
  768.  
  769. ==============================================================================
  770.  
  771. Q72: How is protected inheritance related to private inheritance?
  772.  
  773. Similarities: both allow overriding virtuals in the private/protected base
  774. class, neither claims the derived is a kind-of its base.
  775.  
  776. Dissimilarities: protected inheritance allows derived classes of derived
  777. classes to know about the inheritance relationship (it exposes your grand kids
  778. to your implementation details).  This has both benefits (it allows subclasses
  779. of the protected derived class to exploit the relationship to the protected
  780. base class) and costs (the protected derived class can't change the
  781. relationship without potentially breaking further derived classes).
  782.  
  783. Protected inheritance uses the ": protected" syntax:
  784.  
  785.     class Car : protected Engine {
  786.       //...
  787.     };
  788.  
  789. ==============================================================================
  790.  
  791. Q73: What are the access rules with "private" and "protected" inheritance?
  792.  
  793. Take these classes as examples:
  794.  
  795.     class B                    { /*...*/ };
  796.     class D_priv : private   B { /*...*/ };
  797.     class D_prot : protected B { /*...*/ };
  798.     class D_publ : public    B { /*...*/ };
  799.     class UserClass            { B b; /*...*/ };
  800.  
  801. None of the subclasses can access anything that is private in B.  In D_priv,
  802. the public and protected parts of B are "private".  In D_prot, the public and
  803. protected parts of B are "protected".  In D_publ, the public parts of B are
  804. public and the protected parts of B are protected (D_publ is-a-kind-of-a B).
  805. Class "UserClass" can access only the public parts of B, which "seals off"
  806. UserClass from B.
  807.  
  808. To make a public member of B so it is public in D_priv or D_prot, state the
  809. name of the member with a "B::" prefix.  E.g., to make member "B::f(int,float)"
  810. public in D_prot, you would say:
  811.  
  812.     class D_prot : protected B {
  813.     public:
  814.       B::f;    //note: not  "B::f(int,float)"
  815.     };
  816.  
  817. ==============================================================================
  818. SECTION 13: Abstraction
  819. ==============================================================================
  820.  
  821. Q74: What's the big deal of separating interface from implementation?
  822.  
  823. Interfaces are a company's most valuable resources.  Designing an interface
  824. takes longer than whipping together a concrete class which fulfills that
  825. interface.  Furthermore interfaces require the time of more expensive people.
  826.  
  827. Since interfaces are so valuable, they should be protected from being tarnished
  828. by data structures and other implementation artifacts.  Thus you should
  829. separate interface from implementation.
  830.  
  831. ==============================================================================
  832.  
  833. Q75: How do I separate interface from implementation in C++ (like Modula-2)?
  834.  
  835. Use an ABC (see next FAQ).
  836.  
  837. ==============================================================================
  838.  
  839. Q76: What is an ABC ("abstract base class")?
  840.  
  841. At the design level, an ABC corresponds to an abstract concept.  If you asked a
  842. Mechanic if he repaired Vehicles, he'd probably wonder what KIND-OF Vehicle you
  843. had in mind.  Chances are he doesn't repair space shuttles, ocean liners,
  844. bicycles, or nuclear submarines.  The problem is that the term "Vehicle" is an
  845. abstract concept (e.g., you can't build a "vehicle" unless you know what kind
  846. of vehicle to build).  In C++, class Vehicle would be an ABC, with Bicycle,
  847. SpaceShuttle, etc, being subclasses (an OceanLiner is-a-kind-of-a Vehicle).  In
  848. real-world OOP, ABCs show up all over the place.
  849.  
  850. As programming language level, an ABC is a class that has one or more pure
  851. virtual member functions (see next FAQ).  You cannot make an object (instance)
  852. of an ABC.
  853.  
  854. ==============================================================================
  855.  
  856. Q77: What is a "pure virtual" member function?
  857.  
  858. A member function of an ABC that you can implement only in a derived class.
  859.  
  860. Some member functions exist in concept, but can't have any actual defn.  E.g.,
  861. suppose I asked you to draw a Shape at location (x,y) that has size 7.  You'd
  862. ask me "what kind of shape should I draw?" (circles, squares, hexagons, etc,
  863. are drawn differently).  In C++, we indicate the existence of the "draw()"
  864. method, but we recognize it can (logically) be defined only in subclasses:
  865.  
  866.     class Shape {
  867.     public:
  868.       virtual void draw() const = 0;
  869.       //...                     ^^^--- "= 0" means it is "pure virtual"
  870.     };
  871.  
  872. This pure virtual function makes "Shape" an ABC.  If you want, you can think of
  873. the "= 0" syntax as if the code were at the NULL pointer.  Thus "Shape"
  874. promises a service to its users, yet Shape isn't able to provide any code to
  875. fulfill that promise.  This ensures any actual object created from a [concrete]
  876. class derived of Shape *WILL* have the indicated member fn, even though the
  877. base class doesn't have enough information to actually DEFINE it yet.
  878.  
  879. ==============================================================================
  880.  
  881. Q78: How can I provide printing for an entire hierarchy of classes?
  882.  
  883. Provide a friend operator<< that calls a protected virtual function:
  884.  
  885.     class Base {
  886.     public:
  887.       friend ostream& operator<< (ostream& o, const Base& b)
  888.         { b.print(o); return o; }
  889.       //...
  890.     protected:
  891.       virtual void print(ostream& o) const;  //or "=0;" if "Base" is an ABC
  892.     };
  893.  
  894.     class Derived : public Base {
  895.     protected:
  896.       virtual void print(ostream& o) const;
  897.     };
  898.  
  899. Now all subclasses of Base merely provide their own "print(ostream&) const"
  900. member function (they all share the common "<<" operator).  This technique
  901. allows friends to ACT as if they supported dynamic binding.
  902.  
  903. ==============================================================================
  904.  
  905. Q79: When should my destructor be virtual?
  906.  
  907. When you may "delete" a derived object via a base pointer.
  908.  
  909. Virtual fns bind to the code associated with the class of the object, rather
  910. than with the class of the pointer/ref.  When you say "delete basePtr", and the
  911. base class has a virtual destructor, the destructor that gets invoked is the
  912. one associated with the type of the object *basePtr, rather than the one
  913. associated with the type of the pointer.  This is generally A Good Thing.
  914.  
  915. To make life easy for you, the only time you wouldn't want to make a class's
  916. destructor virtual is if that class has NO virtual fns, since the introduction
  917. of the first virtual fn imposes some space overhead in each object (typically
  918. one machine word).  This is how the compiler implements the magic of dynamic
  919. binding; it usually boils down to an extra ptr per object called the "virtual
  920. table pointer" or "vptr".
  921.  
  922. ==============================================================================
  923.  
  924. Q80: What is a "virtual constructor"?
  925.  
  926. An idiom that allows you to do something that C++ doesn't directly support.
  927.  
  928. You can get the effect of virtual constructor by a virtual "createCopy()"
  929. member fn (for copy constructing), or a virtual "createSimilar()" member fn
  930. (for the default constructor).
  931.  
  932.     class Shape {
  933.     public:
  934.       virtual ~Shape() { }        //see on "virtual destructors" for more
  935.       virtual void draw() = 0;
  936.       virtual void move() = 0;
  937.       //...
  938.       virtual Shape* createCopy() const = 0;
  939.       virtual Shape* createSimilar() const = 0;
  940.     };
  941.  
  942.     class Circle : public Shape {
  943.     public:
  944.       Circle* createCopy()    const { return new Circle(*this); }
  945.       Circle* createSimilar() const { return new Circle(); }
  946.       //...
  947.     };
  948.  
  949. The invocation of "Circle(*this)" is that of copy construction ("*this" has
  950. type "const Circle&" in these methods).  "createSimilar()" is similar, but it
  951. constructs a "default" Circle.
  952.  
  953. Users use these as if they were "virtual constructors":
  954.  
  955.     void userCode(Shape& s)
  956.     {
  957.       Shape* s2 = s.createCopy();
  958.       Shape* s3 = s.createSimilar();
  959.       //...
  960.       delete s2;    //relies on destructor being virtual!!
  961.       delete s3;    // ditto
  962.     }
  963.  
  964. This fn will work correctly regardless of whether the Shape is a Circle,
  965. Square, or some other kind-of Shape that doesn't even exist yet.
  966.  
  967. --
  968. Paradigm Shift, Inc. / P.O. Box 5108 / Potsdam, NY  13676
  969. Technology consulting services
  970. cline@parashift.com / Voice: 315-353-6100 / FAX: 315-353-6110
  971.